package com.onepiece.shipelves.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author guoyanjiang
 * @date 2018/4/13
 */
public class UserAgentUtil {


    private static Pattern IPHONE_PATTERN = Pattern.compile("iPhone OS (.*?) ");
    private static Pattern ANDROID_PATTERN = Pattern.compile("Android (.*?) ");

    public static String getOSVersionNum(String userAgent) {
        Pattern p = null;
        if (userAgent.contains("iPhone")) {
            p = IPHONE_PATTERN;
        } else if (userAgent.contains("Android")) {
            p = ANDROID_PATTERN;
        } else {
            if (userAgent.length() >= 25) {
                return userAgent.substring(0, 25) + "...";
            } else {
                return userAgent;
            }
        }
        Matcher m = p.matcher(userAgent);
        if (m.find()) {
            return m.group(1).replaceAll("_", ".").replaceAll(";", "");
        }
        return userAgent.substring(0, 25) + "...";
    }

    public static void main(String[] args) {
        String ios = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mercury/8.9.4 Mobile/11B554a Safari/9537.53";
        String android = "Dalvik/2.1.0 (Linux; U; Android 6.0.2; SM919 Build/MXB48T)";
        String jmeter = "Apache-HttpClient/4.5.5 (Java/1.8.0_171)";
        System.out.println(getOSVersionNum(ios));
        System.out.println(getOSVersionNum(android));
        System.out.println(getOSVersionNum(jmeter));
        System.out.println(getOSVersionNum("Apache-HttpClient"));
    }
}
